const { app, BrowserWindow, ipcMain, screen } = require('electron');
const path = require('path');

let mainWindow;
let hidden = false; // 标记窗口是否隐藏
const config = {
  edgeBuffer: 20, // 边缘检测的缓冲区大小
  snapDistance: 20, // 吸附距离
  edgeHintSize: 5, // 留给用户的边缘提示大小
  checkInterval: 100, // 每次检查的间隔（毫秒）
  debounceDelay: 300 // 防抖动延迟（毫秒）
};
let lastCheckTime = 0; // 上一次检查的时间

const createWindow = () => {
  mainWindow = new BrowserWindow({
    autoHideMenuBar: true,
    frame: false,
    width: 415,
    height: 415,
    alwaysOnTop: true, // 确保窗口总是位于其他窗口之上
    icon: path.join(__dirname, 'logo.png'), // 指定图标路径
    webPreferences: {
      preload: path.join(__dirname, './preload.js'),
      contextIsolation: true,
      enableRemoteModule: false,
      nodeIntegration: false,
    },
  });

  mainWindow.loadURL('http://localhost:5173/')
    .catch(error => {
      console.error('Failed to load URL:', error);
    });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  // Use setInterval instead of requestAnimationFrame for the main process
  setInterval(checkMousePosition, config.checkInterval);

  ipcMain.on('close-window', () => {
    if (mainWindow) {
      mainWindow.close();
    }
  });
};

app.whenReady().then(() => {
  createWindow();
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow();
  }
});

// 检查鼠标位置
function checkMousePosition() {
  const now = Date.now();
  if (now - lastCheckTime < config.debounceDelay) {
    return; // 防抖动：如果距离上一次检查时间过短，则跳过当前检查
  }
  lastCheckTime = now;

  if (mainWindow) {
    const { x, y, width, height } = mainWindow.getBounds();
    const mousePos = screen.getCursorScreenPoint();
    const display = screen.getDisplayNearestPoint(mousePos);
    const workArea = display.workArea;

    const mouseInWindow = (
      mousePos.x >= x &&
      mousePos.x <= x + width &&
      mousePos.y >= y &&
      mousePos.y <= y + height
    );

    const isSnappedToEdge = (
      x <= workArea.x + config.snapDistance ||
      x + width >= workArea.x + workArea.width - config.snapDistance ||
      y <= workArea.y + config.snapDistance ||
      y + height >= workArea.y + workArea.height - config.snapDistance
    );

    if (hidden) {
      if (mouseInWindow) {
        showWindow(); // 如果鼠标碰到窗口区域，则显示窗口
      }
    } else {
      if (isSnappedToEdge && !mouseInWindow) {
        hideWindow(workArea); // 如果窗口贴边且鼠标不在窗口区域，则隐藏窗口
      }
    }
  }
}

function updateWindowBounds(newBounds) {
  if (mainWindow) {
    mainWindow.setBounds(newBounds);
  }
}

function hideWindow(workArea) {
  if (!hidden && mainWindow) {
    const { x, y, width, height } = mainWindow.getBounds();
    let newX = x, newY = y;

    if (x <= workArea.x + config.snapDistance) {
      newX = workArea.x - width + config.edgeHintSize; // 留边提示
    } else if (x + width >= workArea.x + workArea.width - config.snapDistance) {
      newX = workArea.x + workArea.width - config.edgeHintSize; // 留边提示
    }

    if (y <= workArea.y + config.snapDistance) {
      newY = workArea.y - height + config.edgeHintSize; // 留边提示
    } else if (y + height >= workArea.y + workArea.height - config.snapDistance) {
      newY = workArea.y + workArea.height - config.edgeHintSize; // 留边提示
    }

    if (newX !== x || newY !== y) {
      updateWindowBounds({ x: newX, y: newY, width, height });
      hidden = true;
    }
  }
}

function showWindow() {
  if (hidden && mainWindow) {
    const { x, y, width, height } = mainWindow.getBounds();
    const mousePos = screen.getCursorScreenPoint();
    const display = screen.getDisplayNearestPoint(mousePos);
    const workArea = display.workArea;
    let newX = x, newY = y;

    if (x < workArea.x + config.edgeHintSize) {
      newX = workArea.x + config.snapDistance - 20; // 从左边移动回视图
    } else if (x > workArea.x + workArea.width - width - config.edgeHintSize) {
      newX = workArea.x + workArea.width - width - config.snapDistance + 20; // 从右边移动回视图
    }

    if (y < workArea.y + config.edgeHintSize) {
      newY = workArea.y + config.snapDistance - 20; // 从上边移动回视图
    } else if (y > workArea.y + workArea.height - height - config.edgeHintSize) {
      newY = workArea.y + workArea.height - height - config.snapDistance + 20; // 从下边移动回视图
    }

    if (newX !== x || newY !== y) {
      updateWindowBounds({ x: newX, y: newY, width, height });
      mainWindow.show();
      hidden = false;
    }
  }
}
